﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace Maticsoft.Web.Admin
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["permisscode"].ToString() == "0005")
            {
                Response.Redirect("../");
            }
            //DropDownList1.Items.Clear();
            //BLL.users u = new BLL.users();
            //List<Model.users> us = u.GetModelList(" isverify=0");
            //foreach (Model.users user in us)
            //{
            //    ListItem li = new ListItem();
            //    li.Text = user.name;
            //    li.Value = user.userid.ToString();
            //    DropDownList1.Items.Add(li);
            //}
        }

       
        List<int> jump = new List<int>();
        List<int> jumpnow = new List<int>();
        DataSet dsnew;
        protected void Button1_Click(object sender, EventArgs e)
        {
            BLL.statistics st = new BLL.statistics();
            string where = " isverify=0";
            DataSet ds = st.GetList(where);
            dsnew = new DataSet();
            DataTable dt = new DataTable("showtable");
            dt.Columns.Add("ID");
            dt.Columns.Add("name");
            dt.Columns.Add("type");
            dt.Columns.Add("starttime");
            dt.Columns.Add("endtime");
            dt.Columns.Add("request");
            dt.Columns.Add("finish");
            dt.Columns.Add("other");
            dt.Columns.Add("salarys");
            // dt.Columns.Add("salarysstr");

            dt.Columns.Add("isshow", Type.GetType("System.Boolean"));

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                {

                    string id = ds.Tables[i].Rows[j]["statisticsid"].ToString();
                    if (jump.Contains(Convert.ToInt32(id)))
                        continue;
                    bool isshow = true;//是否显示控制按钮
                    string userid = ds.Tables[i].Rows[j]["userid"].ToString();
                    DateTime date = Convert.ToDateTime(ds.Tables[i].Rows[j]["DATE"].ToString());
                    string name = ds.Tables[i].Rows[j]["name"].ToString();
                    string typename = ds.Tables[i].Rows[j]["assessmentname"].ToString();
                    string type = ds.Tables[i].Rows[j]["TYPE"].ToString();
                    string startdate = "";
                    string enddate = "";
                    int cycle = Convert.ToInt32(ds.Tables[i].Rows[j]["cycle"].ToString());
                    int Irequest = 0;
                    string request = "";
                    string subtype = ds.Tables[i].Rows[j]["subtype"].ToString();
                    int count = 0;
                    int wrodnum = Convert.ToInt32(ds.Tables[i].Rows[j]["wordnum"].ToString());
                    int picnum = Convert.ToInt32(ds.Tables[i].Rows[j]["imgnum"].ToString());
                    string finish = "-";
                    string other = "-";//其他信息
                    string salary = "-";//稿酬
                    double Dsalary = Convert.ToDouble(ds.Tables[i].Rows[j]["perprice"].ToString());//基本价格
                    double PICsalary = Convert.ToDouble(ds.Tables[i].Rows[j]["imgprice"].ToString());//图片价格
                    int uni = Convert.ToInt32(ds.Tables[i].Rows[j]["unit"].ToString());//计算单位
                    string salarySTR = "";
                    switch (type)
                    {
                        case "1"://按任务
                            double basesalary = Convert.ToDouble(ds.Tables[i].Rows[j]["basesalary"].ToString());//基本价格
                            switch (cycle)
                            {
                                case -1://月
                                    break;
                                case -2://年
                                    break;
                                case -3://季
                                    break;
                                case -4://周
                                    startdate = GetMondayDate(date).ToShortDateString();
                                    enddate = GetSundayDate(date).ToShortDateString();
                                    break;
                                default:
                                    break;
                            }


                            Irequest = Convert.ToInt32(ds.Tables[i].Rows[j]["MIN"].ToString());
                            string unit = "-";

                            switch (subtype)//任务时 按字数还是按篇数计算
                            {
                                case "1"://按字数
                                    count = getcount(true, userid, Convert.ToDateTime(startdate), Convert.ToDateTime(enddate), ds);

                                    request = Irequest.ToString() + "字";
                                    unit = "字";
                                    break;
                                case "2"://按篇数
                                    count = getcount(false, userid, Convert.ToDateTime(startdate), Convert.ToDateTime(enddate), ds);

                                    request = Irequest.ToString() + "篇";
                                    unit = "篇";
                                    break;
                                default:
                                    break;
                            }
                            if (jump.Count > 0)//id列表显示在id中
                            {
                                foreach (int ju in jumpnow)
                                {
                                    if (ju.ToString() != id)
                                        id = id + "|" + ju.ToString();
                                }
                            }
                            int tmp = count - Irequest;
                            if (tmp == 0)
                            {
                                finish = "任务完成";
                                salary = Math.Round(basesalary, 2).ToString();
                            }
                            else
                                if (tmp > 0)//超出
                                {
                                    finish = "任务超出";
                                    other = "超出" + tmp + unit;
                                    int overunit = Convert.ToInt32(ds.Tables[i].Rows[j]["overunit"].ToString());//超出奖励，每超出多少字、篇文章奖励
                                    double overprice = Convert.ToDouble(ds.Tables[i].Rows[j]["overprice"].ToString());
                                    double bases = Math.Round(basesalary, 2);
                                    double over = Math.Round((tmp / overunit) * overprice);
                                    salary = (bases + over).ToString();
                                    salarySTR = bases.ToString() + "+" + over.ToString() + "=";
                                }
                                else if (tmp < 0)
                                {
                                    finish = count + unit + "/未完成";
                                    other = "还差" + tmp + unit;
                                    int lessuint = Convert.ToInt32(ds.Tables[i].Rows[j]["lessuint"].ToString());//超出奖励，每超出多少字、篇文章奖励
                                    double lessprice = Convert.ToDouble(ds.Tables[i].Rows[j]["lessprice"].ToString());
                                    double bases = Math.Round(basesalary, 2);
                                    double over = Math.Round((tmp / lessuint) * lessprice);
                                    double all = bases + over;
                                    if (all < 0)
                                        all = 0;
                                    salary = all.ToString();
                                    salarySTR = bases.ToString() + "-" + over.ToString() + "=";
                                }
                                else
                                { }
                            if (Convert.ToDateTime(enddate).Date > DateTime.Now.Date)
                            {
                                other += "--结算日期未到";
                                isshow = false;
                            }
                            break;
                        case "2":
                            startdate = enddate = date.ToShortDateString();
                            request = "按实际字数";
                            finish = "字：" + wrodnum.ToString() + "   图：" + picnum.ToString();
                            double alls = Math.Round((wrodnum / uni) * Dsalary + picnum * PICsalary, 2);
                            salary = alls.ToString();
                            salarySTR = "(" + wrodnum + "/" + uni + ")" + "*" + Dsalary + "+" + picnum + "*" + PICsalary + "=";
                            break;
                        case "3":
                            startdate = enddate = date.ToShortDateString();
                            request = "按实际篇数";
                            finish = "字：" + wrodnum.ToString() + "   图：" + picnum.ToString();
                            int minunit = Convert.ToInt32(ds.Tables[i].Rows[j]["minunit"].ToString());//按篇算时，必须大于多少字
                            int minpic = Convert.ToInt32(ds.Tables[i].Rows[j]["minpic"].ToString());//按篇算时，必须大于多少图
                            if (wrodnum >= minunit && picnum >= minpic)
                            {
                                salary = (Math.Round((1 / uni) * Dsalary, 2)).ToString();
                                salarySTR = "1*" + Dsalary.ToString() + "=";
                            }
                            else
                            {
                                other = "字数或图片不足，字数要求" + minunit.ToString() + "，图片要求" + minpic.ToString();
                                salary = "0";
                                salarySTR = "";
                            }
                            break;
                        default:
                            break;
                    }
                    dt.Rows.Add(id, name, typename, startdate, enddate, request, finish, other, salary, isshow);
                }
            }
            dsnew.Tables.Add(dt);
            GridView1.DataSource = dsnew;
            GridView1.DataBind();
        }
    
        
        
        private int getcount(bool type, string userid, DateTime startdate, DateTime enddate, DataSet ds)
        {
            int count = 0;

            jumpnow.Clear();
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                {
                    string uid = ds.Tables[i].Rows[j]["userid"].ToString();
                    DateTime date = Convert.ToDateTime(ds.Tables[i].Rows[j]["date"].ToString());
                    if (uid == userid && date.Date >= startdate.Date && date <= enddate.Date)
                    {
                        if (type)//字数
                        {
                            int tmp = Convert.ToInt32(ds.Tables[i].Rows[j]["wordnum"].ToString());
                            count += tmp;
                        }
                        else//篇数
                        {
                            count = count+1;
                        }
                        jump.Add( Convert.ToInt32(ds.Tables[i].Rows[j]["statisticsid"].ToString()));
                        jumpnow.Add(Convert.ToInt32(ds.Tables[i].Rows[j]["statisticsid"].ToString()));
                    }
                }
            }
            return count;
        }
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        #region 得到一周的周一和周日的日期

        /// <summary> 
        /// 计算本周的周一日期 
        /// </summary> 
        /// <returns></returns> 
        public static DateTime GetMondayDate()
        {
            return GetMondayDate(DateTime.Now);
        }

        /// <summary> 
        /// 计算本周周日的日期 
        /// </summary> 
        /// <returns></returns> 
        public static DateTime GetSundayDate()
        {
            return GetSundayDate(DateTime.Now);
        }

        ///   <summary>    
        ///   计算某日起始日期（礼拜一的日期）    
        ///   </summary>    
        ///   <param name="someDate">该周中任意一天</param>    
        ///   <returns>返回礼拜一日期，后面的具体时、分、秒和传入值相等</returns>    
        public static DateTime GetMondayDate(DateTime someDate)
        {
            int i = someDate.DayOfWeek - DayOfWeek.Monday;
            if (i == -1) i = 6;//   i值   >   =   0   ，因为枚举原因，Sunday排在最前，此时Sunday-Monday=-1，必须+7=6。    
            TimeSpan ts = new TimeSpan(i, 0, 0, 0);
            return someDate.Subtract(ts);
        }

        ///   <summary>    
        ///   计算某日结束日期（礼拜日的日期）    
        ///   </summary>    
        ///   <param name="someDate">该周中任意一天</param>    
        ///   <returns>返回礼拜日日期，后面的具体时、分、秒和传入值相等</returns>    
        public static DateTime GetSundayDate(DateTime someDate)
        {
            int i = someDate.DayOfWeek - DayOfWeek.Sunday;
            if (i != 0) i = 7 - i;//   因为枚举原因，Sunday排在最前，相减间隔要被7减。    
            TimeSpan ts = new TimeSpan(i, 0, 0, 0);
            return someDate.Add(ts);
        }

        #endregion

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowindex=Convert.ToInt32(e.CommandArgument.ToString());
            string idstr = ((Label)GridView1.Rows[rowindex].FindControl("Lid")).Text;
         
            string[] ids = idstr.Split(new char[]{ '|'},StringSplitOptions.RemoveEmptyEntries);

            string reason = ((TextBox)GridView1.Rows[rowindex].FindControl("TBreason")).Text;
            BLL.statistics sta = new BLL.statistics();
            Model.statistics stamod = new Model.statistics();
            switch (e.CommandName)
            {
                case "up"://提交
                   
                    BLL.salarystatistics sal = new BLL.salarystatistics();
                    Model.salarystatistics salmod = new Model.salarystatistics();
                    foreach (string s in ids)
                    {
                        int id = Int32.Parse(s);
                        stamod = sta.GetModel(id);
                        stamod.isverify = 1;
                        sta.Update(stamod);//更新审核标记
                    }
                        salmod.ispay = 0;
                        salmod.originalsalarys = Convert.ToDouble(((Label)GridView1.Rows[rowindex].FindControl("Lsalarys")).Text);
                       // salmod.other = ((Label)GridView1.Rows[rowindex].FindControl("Lother")).Text;
                        BLL.users u = new BLL.users();
                        Model.users umod = u.GetModel(stamod.userid);

                        salmod.payid = umod.payinfo;//支付帐号
                        salmod.reason= ((TextBox)GridView1.Rows[rowindex].FindControl("TBreason")).Text;//原因
                        salmod.salarys = Convert.ToDouble(((Label)GridView1.Rows[rowindex].FindControl("Lsalarys")).Text) + Convert.ToDouble(((TextBox)GridView1.Rows[rowindex].FindControl("TBmoney")).Text);
                        salmod.salarysenddate = Convert.ToDateTime(((Label)GridView1.Rows[rowindex].FindControl("Lend")).Text);
                        salmod.salarysstartdate = Convert.ToDateTime(((Label)GridView1.Rows[rowindex].FindControl("Lstart")).Text);
                        salmod.userid = 0;
                        salmod.verify = 0;
                        salmod.verifyid = 0;
                        salmod.Statisticsid = stamod.userid;//用户ID
                        sal.Add(salmod);
                        Page.RegisterStartupScript("success", "<script>alert('提交财务处理成功！')</script>");
                        Button1_Click(null,null);//刷新
                     
                    break;
                case "gaveup"://作废
                    foreach (string s in ids)
                    {
                        int id = Int32.Parse(s);
                        stamod = sta.GetModel(id);
                        stamod.isverify =-1;
                        stamod.other = ((TextBox)GridView1.Rows[rowindex].FindControl("TBreason")).Text;
                        sta.Update(stamod);//更新审核标记
                    }
                    Page.RegisterStartupScript("success", "<script>alert('作废处理成功！')</script>");
                     Button1_Click(null,null);//刷新
                    break;
                default:
                    break;
            }
            GridView1.DataBind();
        }
    }
}